import { createClient, getSrc } from '@/utils/ik/oss/oss.js'

export function uploadFile(file) {
  const key = getKey(file.type)
  const header = {
    "x-oss-forbid-overwrite": true,
    "Sec-Fetch-Dest": "image",
    "Sec-Fetch-Mode": "no-cors",
    "Sec-Fetch-Site": "cross-site"
  }
  return new Promise((resolve, reject) => {
    const client = createClient()
    client.put(key, file, header)
      .then(() => {
        const imageUrl = getSrc(client, key)
        resolve(imageUrl)
      })
      .catch(error => {
        reject(error)
      })
  })
}

/**
 * 获取图片key
 * @param fileType
 */
function getKey(fileType) {
  let type
  switch (fileType) {
    case 'image/jpeg':
      type = 'jpeg'
      break
    case 'image/jpg':
      type = 'jpg'
      break
    case 'image/gif':
      type = 'gif'
      break
    case 'image/png':
      type = 'png'
      break
  }
  return 'test/time=' + new Date().getTime() + '&id=' + guidGenerator() + '.' + type// 存储路径，并且给图片改成唯一名字
}

/**
 * 签名
 * @returns {string}
 */
function guidGenerator() {
  const S4 = function() {
    return ((1 + Math.random()) * 0X10000 | 0).toString(16).substring(1)
  }
  return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4())
}
